package cn.ex.de001.interceConf;

import cn.ex.de001.common.utils.tokenUtils.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Objects;

@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {

    private static final long fixedTime = 300;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 只对 HandlerMethod 类型的处理器进行拦截
        //判断用户携带的token是否存在于白名单内
        String token=request.getHeader("token");
        String account= Token.getAccount(token);//通过token获取用户账号
        String usingToken= Token.map.get(account);//获取该用户最新的有效token
        if(!Objects.equals(token, usingToken)){//该token已经失效
            response.setStatus(401);
            return false;
        }
        //检查token / 更新token
        if(Token.checkSign(token)){
            Long time = Token.expiration(token);
            if (time <= fixedTime){
                Token.map.remove(account);//移出白名单
                String sign = Token.sign(account);
                Token.map.put(account,sign);//将新的token移入有效token
            }
            return true;
        } else {
            response.setStatus(401);
            return false;
        }
    }


  /*  private boolean isTokenExpired(SpUserToken spUserToken) {
        // 检查 token 是否过期
        long expireTime = spUserToken.getExpiretime();
        long currentTimeInSeconds = System.currentTimeMillis() / 1000;
        return currentTimeInSeconds >= expireTime;
    }

    private boolean handleException(HttpServletResponse response, Integer code, String msg) throws IOException {
        BusinessException exception = new BusinessException();
        exception.setCode(code);
        exception.setMsg(msg);
        String obj = JSONObject.toJSONString(exception);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(obj);
        response.setStatus(HttpServletResponse.SC_OK); // 设置适当的 HTTP 状态码
        return false; // 拦截请求
    }

    *//* controller执行后，页面渲染前*//*
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {}

    *//* 页面渲染后*//*
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e){
        UserContext.clear(); // 清理 ThreadLocal
    }*/

}

